package cn.itsource.pethome.order.service.impl;


import cn.itsource.pethome.Basic.domain.Point;
import cn.itsource.pethome.Basic.service.Impl.BaseServiceImpl;
import cn.itsource.pethome.Basic.util.CodeGenerateUtils;
import cn.itsource.pethome.Basic.util.DistanceUtil;
import cn.itsource.pethome.order.domain.OrderAddress;
import cn.itsource.pethome.order.domain.ProductOrder;
import cn.itsource.pethome.order.domain.ProductOrderDetail;
import cn.itsource.pethome.order.domain.UserAddress;
import cn.itsource.pethome.order.mapper.OrderAddressMapper;
import cn.itsource.pethome.order.mapper.ProductOrderDetailMapper;
import cn.itsource.pethome.order.mapper.ProductOrderMapper;
import cn.itsource.pethome.order.mapper.UserAddressMapper;
import cn.itsource.pethome.order.service.IProductOrderService;
import cn.itsource.pethome.org.domain.Shop;
import cn.itsource.pethome.org.mapper.ShopMapper;
import cn.itsource.pethome.pay.constant.PayConstants;
import cn.itsource.pethome.pay.domain.PayBill;
import cn.itsource.pethome.pay.service.IPayBillService;
import cn.itsource.pethome.product.domain.Product;
import cn.itsource.pethome.product.mapper.ProductMapper;
import cn.itsource.pethome.quartz.domain.QuartzJobInfo;
import cn.itsource.pethome.quartz.service.IQuartzJobInfoService;
import cn.itsource.pethome.user.domain.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
@Transactional
public class ProductOrderServiceImpl extends BaseServiceImpl<ProductOrder> implements IProductOrderService{
    //订单mapper
    @Autowired
    private ProductOrderMapper productOrderMapper;
    //用户地址mapper
    @Autowired
    private UserAddressMapper userAddressMapper;
    //商铺mapper
    @Autowired
    private ShopMapper shopMapper;
    //服务mapper
    @Autowired
    private ProductMapper productMapper;
    //订单详情mapper
    @Autowired
    private ProductOrderDetailMapper productOrderDetailMapper;
    //订单地址mapper
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    //支付订单mapper
    @Autowired
    private IPayBillService payBillService;
    //定时器mapper
    @Autowired
    private IQuartzJobInfoService quartzJobInfoService;
    @Override
    public String submitOrder(Map<String, Object> param, User loginUser) {
        //通过用户获取地址id
        System.out.println(param);
        Integer addressId = (Integer) param.get("addressId");
        //通过用户地址id获取地址
        UserAddress userAddress = userAddressMapper.loadUserAddressById(addressId);
        //通过用户地址对象获取用户地址
        String fullAddress = userAddress.getFullAddress();
        //将用户地址字符串转换为经纬度
        Point point = DistanceUtil.getPoint(fullAddress);
        //分配最近商铺
        Shop shop = DistanceUtil.getNearestShop(point, shopMapper.loadAllShop());
        //获取用户所点服务
        List<Map<String,Object>> products =(List<Map<String,Object>>)param.get("products");
        //获取支付方式
        Integer payType = (Integer) param.get("payType");
        //创建服务订单
        ProductOrder productOrder = createProductOrder(loginUser, payType, shop, products);
        //保存订单信息
        productOrderMapper.add(productOrder);
        //创建订单详情
        List<ProductOrderDetail> productOrderDetails = creatProductOrderDetail(products, productOrder);
        //保存订单详情
        productOrderDetailMapper.batchSave(productOrderDetails);
        //创建订单地址
        OrderAddress orderAddress = userAddressToOrderAddress(userAddress, productOrder);
        //保存订单地址
        orderAddressMapper.add(orderAddress);
        //创建支付订单
        PayBill payBill = createPayOrder(productOrder);
        //保存支付订单
        payBillService.add(payBill);
        //跳转支付界面
        String formhtml = payBillService.goPay(payBill);
        //设置定时器
        QuartzJobInfo quartzJobInfo = createQuqrtz(productOrder);
        //保存
        quartzJobInfoService.addJob(quartzJobInfo);
        //保存定时器
        return formhtml;
    }

    /**
     * 创建定时器
     * @param productOrder
     * @return
     */
    private QuartzJobInfo createQuqrtz(ProductOrder productOrder) {
        QuartzJobInfo jobInfo = new QuartzJobInfo();
        //设置处理类型
        jobInfo.setType(PayConstants.BUSINESSTYPE_PRODUCT+productOrder.getId());
        //设置触发时间
        jobInfo.setFireDate(productOrder.getLastPayTime());
        //设置任务名
        jobInfo.setJobName(PayConstants.BUSINESSTYPE_PRODUCT);
        //设置参数
        Map<String,Object> params = new HashMap<>();
        params.put("params",params);
        jobInfo.setParams(params);
        return jobInfo;
    }

    /**
     * 将用户地址复制到订单地址
     * @param userAddress
     * @param productOrder
     */
    public OrderAddress userAddressToOrderAddress(UserAddress userAddress, ProductOrder productOrder) {
        //创建订单地址
        OrderAddress orderAddress = new OrderAddress();
        //复制用户下单地址
        BeanUtils.copyProperties(userAddress,orderAddress);
        //保存订单对象
        orderAddress.setOrder(productOrder);
        //保存订单编号
        orderAddress.setOrderSn(productOrder.getOrderSn());
        //设置创建时间
        orderAddress.setCreateTime(new Date());
        return orderAddress;
    }

    /**
     * 创建订单详情
     * @param products
     * @param productOrder
     */
    public List<ProductOrderDetail> creatProductOrderDetail(List<Map<String, Object>> products, ProductOrder productOrder) {
        //生成订单详情
        List<ProductOrderDetail> productOrderDetails = new ArrayList<>();
        //设置服务
        for (Map<String, Object> product : products) {
            //获取服务id
            Integer id = (Integer) product.get("id");
            //获取服务数量
            Integer num = (Integer) product.get("num");
            //通过服务id获取服务对象
            Product product1 = productMapper.findById(Long.valueOf(id));
            ProductOrderDetail productOrderDetail = new ProductOrderDetail();
            //存入服务对象
            productOrderDetail.setProduct(product1);
            //存入订单对象
            productOrderDetail.setOrder(productOrder);
            //存入服务数量
            productOrderDetail.setSaleCount(num);
            productOrderDetails.add(productOrderDetail);
        }
        return productOrderDetails;
    }

    /**
     * 创建订单
     * @param loginUser
     * @param shop
     * @param products
     */
    public ProductOrder createProductOrder(User loginUser,Integer payType, Shop shop, List<Map<String, Object>> products) {
        ProductOrder order = new ProductOrder();
        //设置摘要
        order.setDigest("[服务订单]"+ shop.getName()+"为你服务");
        //设置支付方式
        order.setPayType(payType);
        //设置支付状态
        order.setState(0);
        //设置价格
        BigDecimal bigDecimal = new BigDecimal("0");
        for (Map<String, Object> product : products) {
            //获取服务id
            Integer id = (Integer) product.get("id");
            //获取服务数量
            Integer num =(Integer) product.get("num");
            //通过服务id获取服务对象
            Product product1 = productMapper.findById(Long.valueOf(id));
            //通过服务对象获取售价
            BigDecimal saleprice = product1.getSaleprice();
            //计算总计金额
            bigDecimal = saleprice.multiply(new BigDecimal(num));
        }
        order.setPrice(bigDecimal);
        //生成订单编号编号
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(loginUser.getId()));
        //设置最后支付时间
        order.setLastPayTime(new Date(System.currentTimeMillis()+80*1000));
        //设置下单用户
        order.setUser(loginUser);
        //设置商铺
        order.setShop(shop);
        //保存订单
        return order;
    }

    /**
     * 创建支付订单
     * @return
     */
    private PayBill createPayOrder(ProductOrder productOrder) {
        PayBill payBill = new PayBill();
        //设置摘要
        payBill.setDigest(productOrder.getDigest());
        //设置支付状态 0 待支付
        payBill.setState(0);
        //设置价格
        payBill.setMoney(productOrder.getPrice());
        //设置最后支付时间
        payBill.setLastPayTime(productOrder.getLastPayTime());
        //设置支付方式 //0 余额 1 支付宝 2 微信 3 银联
        payBill.setPayChannel(1L);
        //设置创建时间
        payBill.setCreateTime(new Date());
        //设置用户
        payBill.setUser(productOrder.getUser());
        //设置商铺
        payBill.setShop(productOrder.getShop());
        //设置业务类型
        payBill.setBusinessType(PayConstants.BUSINESSTYPE_PRODUCT);
        //设置业务主键
        payBill.setBusinessKey(productOrder.getId());
        //设置订单编号
        payBill.setOrderSn(productOrder.getOrderSn());
        return payBill;
    }
}
